import { NavigateFunction } from 'react-router-dom';
import { message } from 'antd';
import { store } from '../store';
import { logout } from '../store/slices/auth';

/**
 * 获取本地存储的token
 */
export const getToken = (): string | null => {
    return localStorage.getItem('token');
};

/**
 * 设置token到本地存储
 * @param token 认证令牌
 */
export const setToken = (token: string): void => {
    localStorage.setItem('token', token);
};

/**
 * 移除本地存储的token
 */
export const removeToken = (): void => {
    localStorage.removeItem('token');
};

/**
 * 获取本地存储的菜单
 */
export const getMenus = (): any[] => {
    try {
        const menus = localStorage.getItem('menus');
        return menus ? JSON.parse(menus) : [];
    } catch (error) {
        console.error('Failed to parse menus from storage', error);
        return [];
    }
};

/**
 * 设置菜单到本地存储
 * @param menus 菜单数据
 */
export const setMenus = (menus: any[]): void => {
    localStorage.setItem('menus', JSON.stringify(menus));
};

/**
 * 移除本地存储的菜单
 */
export const removeMenus = (): void => {
    localStorage.removeItem('menus');
};

/**
 * 检查用户是否已登录
 */
export const isLoggedIn = (): boolean => {
    return !!getToken();
};

/**
 * 执行登出操作
 * @param navigate 路由导航函数
 */
export const handleLogout = (navigate: NavigateFunction): void => {
    store.dispatch(logout());
    navigate('/login');
    message.success('已退出登录');
};

/**
 * 检查token是否过期（示例实现，实际项目中可能需要解析JWT或其他逻辑）
 */
export const isTokenExpired = (): boolean => {
    // 这里仅为示例，实际项目中应根据token类型进行具体实现
    // 如果使用JWT，可以解析token并检查exp字段
    return false;
};

/**
 * 处理token过期情况
 * @param navigate 路由导航函数
 */
export const handleTokenExpired = (navigate: NavigateFunction): void => {
    store.dispatch(logout());
    navigate('/login');
    message.error('登录已过期，请重新登录');
}; 